package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.entity.Result;
import com.qingcheng.service.seckill.SeckillOrderService;
import com.qingcheng.util.SeckillStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:boy
 * @Date:2019/7/23
 * @description:
 * @ModifiedBy:
 */
@RestController
@RequestMapping("/seckill/order")
public class SeckillOrderController {
    @Reference
    private SeckillOrderService seckillOrderService;

    @GetMapping("/add")
    public Result add(String startTime, Long id) {
        try {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            if ("anonymousUser".equals(username)) {
                return new Result(403, "用户未登录");
            }
            boolean result = seckillOrderService.add(id, startTime, username);
            if (result) {
                return new Result(0, "秒杀下单成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1, e.getMessage());
        }
        return new Result(1, "秒杀下单失败");
    }

    @GetMapping("/query")
    public Result queryStatus() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        if ("anonymousUser".equals(username)) {
            return new Result(403, "用户未登录");
        }
        SeckillStatus seckillStatus = seckillOrderService.queryStatus(username);
        if (seckillStatus != null) {
            Result result = new Result(seckillStatus.getStatus(), "抢购状态");
            result.setOther(seckillStatus);
            return result;
        }
        return new Result(404, "无秒杀订单信息");
    }

}
